package df.bean.obj.doctor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.List;

import df.bean.db.conn.DBConnection;
import df.bean.db.table.Batch;
import df.bean.db.table.PaymentMode;
import df.bean.db.table.StpMethodAllocItem;
import df.bean.db.table.StepSharing;
import df.bean.db.table.SummaryMonthly;
import df.bean.db.table.SummaryMonthlyStep;
import df.bean.db.table.TRN_Error;
import df.bean.obj.util.JDate;
import df.bean.obj.util.Variables;
import df.bean.obj.variable.SummaryMonthlyVar;


public class DrFullTime extends CareProvider {
    List stepSharingList = null;
//    public static SummaryMonthlyVar smVar = null;
    public static SummaryMonthlyVar smVarStep = null;
    
    public DrFullTime() {
        super();
    }
    
    public DrFullTime(String doctorCode, String hospitalCode, DBConnection conn) {
        super(doctorCode, hospitalCode, conn);
    }
    
    @Override
    protected void finalize() {
        stepSharingList.clear();
        stepSharingList = null;
    }
    
    public void newStepSharing() {
        String Code = this.getDBConnection().executeQueryString("select DOCTOR_CATEGORY.DOCTOR_CLASS_CODE from DOCTOR,DOCTOR_CATEGORY where DOCTOR.CODE='" + this.getDoctorCode() + "' and " + "DOCTOR.DOCTOR_CATEGORY_CODE=DOCTOR_CATEGORY.CODE");
        String sqlCommand = "select * from STEP_SHARING where DOCTOR_CLASS_CODE='" + Code + "' order by SORDER";
        ResultSet rs = null;
        setStepSharingList(new ArrayList());
        Statement stmt = null;
        try {
            stmt = this.getDBConnection().getConnection().createStatement();
            rs = stmt.executeQuery(sqlCommand);
            while (rs.next()) {
                getStepSharingList().add(new StepSharing(rs.getString("Code"), rs.getString("DOCTOR_CLASS_CODE"), this.getDBConnection()));
            }    
            rs.close();
            stmt.close();

        } catch (SQLException e) {
            e.printStackTrace();
            TRN_Error.writeErrorLog(this.getDBConnection().getConnection(),
                    this.getClass().getName(), "", e.getMessage());
        }
        rs = null;
        stmt = null;        
    }

    public List<StepSharing> getStepSharingList() {
        return stepSharingList;
    }

    public void setStepSharingList(List stepSharingList) {
        this.stepSharingList = stepSharingList;
    }

    /*protected boolean computeMethodAllocation() {
        // call for get TAX_TYPE_CODE
        this.lNorAllocatePct = 100d;
        this.lNorAllocateAmt = 0d;
        this.lDrAmt = this.lInvAmt; //receipt.getReceiptDetail().getAmountAftDiscount();
        this.lHpAmt = 0d;
        
        return true;
    }*/
    
    @Override
    public boolean computePremium() {
        // if patient was paid by credit card 
        // �������ͻ�Ш�  þ. �͡��� 100%
        super.computePremium();
        if (!this.lExcludeTreatment.equals(StpMethodAllocItem.EXCLUDE_YES)) {
            this.lHpPremium = Double.parseDouble((new java.text.DecimalFormat("0.00")).format(this.lTotPremiumAmt));
            this.lDrPremium = 0.00;
        }
        return true;
    }
    

// ----------------------------- Transaction Monthly -------------------------- //
 // ----------------------------- Transaction Monthly -------------------------- //
  // ----------------------------- Transaction Monthly -------------------------- //
   // ----------------------------- Transaction Monthly -------------------------- //
    // ----------------------------- Transaction Monthly -------------------------- //
     // ----------------------------- Transaction Monthly -------------------------- //
 
    @Override
     public boolean computeTransMonthly() {
         boolean result = false;
         try {
             // call for compute summary step rate and include treatment
             SummaryMonthly sm = new SummaryMonthly(this.getDBConnection());
             result = this.computeTransactionMonthlyStep(sm);
             if (!result) { sm = null; return false; }
             
             // call for exclude treatment
             SummaryMonthly smEx = new SummaryMonthly(this.getDBConnection());
             result = this.computeTransactionMonthly(smEx);
             if (!result) { smEx = null; return false; }
             
             // insert into SUMMARY_MONTHLY table
             //                sm.setBatchNo(" ");
             sm.setHospitalCode(this.getHospitalCode());
             sm.setDoctorCode(this.getDoctorCode());
             sm.setYyyy(Batch.getYyyy());
             sm.setMm(Batch.getMm());
             sm.setTransactionDate(JDate.getDate());
             
             sm.setSumAmt(sm.getSumAmt() + smEx.getSumAmt());
             sm.setSumDiscAmt(sm.getSumDiscAmt() + smEx.getSumDiscAmt());
             sm.setSumPatientPaidAmt(sm.getSumPatientPaidAmt() + smEx.getSumPatientPaidAmt());
             sm.setSumPremiumAmt(sm.getSumPremiumAmt() + smEx.getSumPremiumAmt());
             sm.setDrSumAmt(sm.getDrSumAmt() + smEx.getDrSumAmt());
             sm.setDrTax402(sm.getDrTax402() + smEx.getDrTax402());
             sm.setDrTax406(sm.getDrTax406() + smEx.getDrTax406());
             sm.setDrPremiumAmt(sm.getDrPremiumAmt() + smEx.getDrPremiumAmt());
             sm.setHpSumAmt(sm.getHpSumAmt() + smEx.getHpSumAmt());
             sm.setHpPremiumAmt(sm.getHpPremiumAmt() + smEx.getHpPremiumAmt());
             sm.setHpTax(sm.getHpTax() + smEx.getHpTax());
             sm.setSumPremiumRecAmt(sm.getSumPremiumRecAmt());
     
     
             double gaurunteeAmt = 0d;
             
             // ���� payroll paid and payroll tax 40(2)                                 
             sm.setGuarunteeAmt(gaurunteeAmt);
             sm.setGuarunteeTax(gaurunteeAmt);
             
             sm.setDrCreditAmt(0.0);
             // get expense
//             TrnExpenseHeader exp = new TrnExpenseHeader(Batch.getYyyy(),Batch.getMm(), Batch.getHospitalCode(), this.getDoctorCode(), this.getDBConnection());
//             sm.setDrCreditAmt(exp.getCreditAmount());
//             sm.setDrDebitAmt(exp.getDebitAmount());
             sm.setDrCreditAmt(0d);
             sm.setDrDebitAmt(0d);
             sm.setDrDiscAmt(0.0);
             sm.setHpDiscAmt(0.0);
             
             double drNetPaidAmt = sm.getDrSumAmt() - sm.getDrDiscAmt() - sm.getDrPremiumAmt() 
                                     - sm.getDrCreditAmt() + sm.getDrDebitAmt(); // + sm.getGuarunteeAmt();
                                     
             sm.setDrNetPaidAmt(drNetPaidAmt);
             sm.setUserID(Variables.getUserID());
             sm.setBatchNo("");
             sm.setStatusModify("");
             sm.setUpdateDate(JDate.getDate());
             sm.setUpdateTime(JDate.getTime());
             sm.setOldDoctorCode(this.getDoctorCode());
             
             //sm.setRemark(Utils.toThaiMoney(sm.getDrNetPaidAmt()));
             sm.setRemark("");
             sm.setRefPaidNo(this.getDoctor().getBankAccountNo());
             sm.setPaymentModeCode(this.getDoctor().getPaymentModeCode());
             
             // Payment
             if (sm.getPaymentModeCode().equals(PaymentMode.PAYMENT_CHEQUE)) {  sm.setPayDate("");  } 
             else { sm.setPayDate(Batch.getPaymentDate()); }
             sm.setPaymentTermDate(Batch.getPaymentDate());
             sm.setIsHold(this.getDoctor().getIsHold());
             
             // ===========================================//
//            if ((sm.getDrSumAmt() != 0) || (sm.getDrDiscAmt() != 0) || (sm.getDrPremiumAmt() !=0) || (sm.getDrCreditAmt() != 0) || (sm.getDrDebitAmt()!=0)) {
             if (drNetPaidAmt != 0 ) {
                 if (!sm.insert()) {       
                     sm = null;
                     smEx = null;
                     return false;
                 }
             }
     
             sm = null;
             smEx = null;                
         } catch (Exception e) {
             e.printStackTrace();
             TRN_Error.writeErrorLog(this.getDBConnection().getConnection(),
                    this.getClass().getName(), "", e.getMessage());
             return false;
             } finally {
                //Clean up resources, close the connection.
                 try {
    
                 } catch (Exception ignored) { ignored.printStackTrace();   }
             }
    
         return true;
     }
     
     // Exclude treatment = 'N'
     // Command is the same Careprovider
     public boolean computeTransactionMonthlyStep(SummaryMonthly sm) {
        String sql = SummaryMonthly.getSQLSum_DAILYwithExcludeTreatment_N(this.getHospitalCode());
         
         if (smVarStep == null) {
             smVarStep = new SummaryMonthlyVar(this.conn);
             smVarStep.getDataByQuery(sql);
         }
         
         if (smVarStep.IsFoundAndSetData(this.getDoctorCode())) {
                 
                     double totAmt=0;
                     List drMoneyLst = new ArrayList();
                     List hpMoneyLst = new ArrayList();
                     totAmt = smVarStep.getSumDrAmt();
                 //                this.setDoctorCode(rs.getString("DOCTOR_CODE"));
                     this.newStepSharing();
                     
                     // ����� ��äӹǳẺ��鹺ѹ�
                     for (int i=0; i<this.stepSharingList.size(); i++) {
                         String code = ((StepSharing)this.stepSharingList.get(i)).getCode();
                         double beginAmt = ((StepSharing)this.stepSharingList.get(i)).getBeginAmount();
                         double endAmt = ((StepSharing)this.stepSharingList.get(i)).getEndAmount();
                         double drPct = ((StepSharing)this.stepSharingList.get(i)).getDrPercent();
                         double hpPct = ((StepSharing)this.stepSharingList.get(i)).getHpPercent();
                         double SORDER = ((StepSharing)this.stepSharingList.get(i)).getSorder();
                         double drMoney = 0, hpMoney = 0;
                         
                         double rest = beginAmt - Double.parseDouble((new java.text.DecimalFormat("0.0")).format(beginAmt));
                         rest = Double.parseDouble((new java.text.DecimalFormat("0.00")).format(rest));
                         
                         if (totAmt > endAmt) {
                             // �ҡ���Ҥ�� �ش����
                             drMoney = (endAmt - (beginAmt - rest)) * (drPct / 100);
                             hpMoney = (endAmt - (beginAmt - rest)) * (hpPct / 100);
                         } else if ((totAmt >= beginAmt) && (totAmt <= endAmt)){
                             // ������������ҧ �������u� ��� ����ش����
                             drMoney = (totAmt - (beginAmt - rest)) * (drPct / 100);
                             hpMoney = (totAmt - (beginAmt - rest)) * (hpPct / 100);
                         } else {  
                             // ���¡��Ҥ������u�
                             drMoney = 0;
                             hpMoney = 0;
                         }
                         
                         drMoneyLst.add(drMoney);
                         hpMoneyLst.add(hpMoney);
                         
                         // insert into Summary Monthly Step
                         SummaryMonthlyStep sms = new SummaryMonthlyStep(this.getDBConnection());
                         sms.setDoctorCode(this.getDoctorCode());
                         sms.setDrAmt(drMoney);
                         sms.setDrPercent(drPct);
                         sms.setHpPercent(hpPct);
                         sms.setHospitalCode(this.getHospitalCode());
                         sms.setHpAmt(hpMoney);
                         sms.setMm(Batch.getMm());
                         sms.setYyyy(Batch.getYyyy());
                         sms.setSorder(SORDER);
                         sms.setStepSharingCode(code);
                         sms.setUpdateDate(JDate.getDate());
                         sms.setUpdateTime(JDate.getTime());
                         sms.setUserId(Variables.getUserID()); 
                         sms.setOldDoctorCode(this.getDoctorCode());
                         
                         if (!sms.insert())  {
                             this.setMessage("Can't insert data into table !!!!");
                             sms = null;
                             return false;
                         }
                         sms = null;
                     } // ����ش��÷ӧҹẺ��鹺ѹ�
                     
                     // �ӹǳ�Ҽ���bͧ���������͹
                     double sumDr = 0, sumHp = 0;
                     for (int i=0; i<drMoneyLst.size(); i++) {
                         sumDr = sumDr + Double.parseDouble(drMoneyLst.get(i).toString());
                         sumHp = sumHp + Double.parseDouble(hpMoneyLst.get(i).toString());
                     }
                     
                     sm.setHospitalCode(this.getHospitalCode());
                     sm.setDoctorCode(this.getDoctorCode());
                     sm.setYyyy(Batch.getYyyy());
                     sm.setMm(Batch.getMm());
                     sm.setTransactionDate(JDate.getDate());

                     sm.setSumAmt(smVarStep.getSumAmountAftDiscount());
                     sm.setSumDiscAmt(smVarStep.getSumAmountOfDiscount());
                     sm.setSumPatientPaidAmt(smVarStep.getSumRecAmountAftDiscount());
                     sm.setSumPremiumAmt(smVarStep.getSumRecPremiumAmt());
                     sm.setDrSumAmt(sumDr);
                     sm.setDrTax400(smVarStep.getSumDrAmt_400());
                     sm.setDrTax401(smVarStep.getSumDrAmt_401());
                     sm.setDrTax402(smVarStep.getSumDrAmt_402());
                     sm.setDrTax406(smVarStep.getSumDrAmt_406());
                     sm.setDrPremiumAmt(smVarStep.getSumDrPremium());
                     sm.setHpSumAmt(sumHp);
                     sm.setHpPremiumAmt(smVarStep.getSumHpPremium());
                     sm.setHpTax(smVarStep.getSumHpTax());
                     sm.setDrStepAmt(sumDr);
                     sm.setHpStepAmt(sumHp);
                     sm.setSumPremiumRecAmt(smVarStep.getSumPremiumRecAmt());
                     sm.setDrDiscAmt(0.0);
                     sm.setHpDiscAmt(0.0); 
                     
                     
                     //เพิ่มทีหลัง  ยังไม่ได้ตรวจสอบว่าต้องเพิ่มตรงนี้ด้วยหรือเปล่า
                    sm.setSumPayByCash(smVarStep.getSumPayByCash());
                    sm.setSumPayByAR(smVarStep.getSumPayByAR());
                    sm.setCashAmt(smVarStep.getCashAmt());
                    sm.setCash400(smVarStep.getCash400());
                    sm.setCash401(smVarStep.getCash401());
                    sm.setCash402(smVarStep.getCash402());
                    sm.setCash406(smVarStep.getCash406());
                    sm.setArAmt(smVarStep.getArAmt());
                    sm.setAr400(smVarStep.getAr400());
                    sm.setAr401(smVarStep.getAr401());
                    sm.setAr402(smVarStep.getAr402());
                    sm.setAr406(smVarStep.getAr406());
                    drMoneyLst = null;
                    hpMoneyLst = null; 
                }            
                return true;
     }
    
    
     // code ����͹ CareProvider ���� sql = EXCLUDE_TREATMENT = 'Y'
     public boolean computeTransactionMonthly(SummaryMonthly sm) {
        String sql = SummaryMonthly.getSQLSum_DAILYwithExcludeTreatment_Y(this.getHospitalCode());
         
        if (smVar == null) {  
         smVar = new SummaryMonthlyVar(this.conn); 
         smVar.getDataByQuery(sql);
        }

        if (smVar.IsFoundAndSetData(this.getDoctorCode())) {
            sm.setSumAmt(smVar.getSumAmountAftDiscount());
            sm.setSumDiscAmt(smVar.getSumAmountOfDiscount());
            sm.setSumPatientPaidAmt(smVar.getSumRecAmountAftDiscount());
            sm.setSumPremiumAmt(smVar.getSumRecPremiumAmt());
            sm.setDrSumAmt(smVar.getSumDrAmt());
            sm.setDrTax400(smVar.getSumDrAmt_400());
            sm.setDrTax401(smVar.getSumDrAmt_401());
            sm.setDrTax402(smVar.getSumDrAmt_402());
            sm.setDrTax406(smVar.getSumDrAmt_406());
            sm.setDrPremiumAmt(smVar.getSumDrPremium());
            sm.setHpSumAmt(smVar.getSumHpAmt());
            sm.setHpPremiumAmt(smVar.getSumHpPremium());
            sm.setHpTax(smVar.getSumHpTax());
            sm.setSumPremiumRecAmt(smVar.getSumPremiumRecAmt());
            sm.setDrDiscAmt(0.0);
            sm.setHpDiscAmt(0.0); 
            sm.setSumPayByCash(smVar.getSumPayByCash());
            sm.setSumPayByAR(smVar.getSumPayByAR());
            sm.setCashAmt(smVar.getCashAmt());
            sm.setCash400(smVar.getCash400());
            sm.setCash401(smVar.getCash401());
            sm.setCash402(smVar.getCash402());
            sm.setCash406(smVar.getCash406());
            sm.setArAmt(smVar.getArAmt());
            sm.setAr400(smVar.getAr400());
            sm.setAr401(smVar.getAr401());
            sm.setAr402(smVar.getAr402());
            sm.setAr406(smVar.getAr406());
        }
        return true;
    }
    // ----------------------------- End of Transaction Monthly -------------------------- //
     // ----------------------------- End of Transaction Monthly -------------------------- //
      // ----------------------------- End of Transaction Monthly -------------------------- //
       // ----------------------------- End of Transaction Monthly -------------------------- //
       
}


